package com.rw.coco.handler.message.reply.handler.validate;

import com.rw.coco.api.log.CocoLogger;
import com.rw.coco.api.modle.Account;
import com.rw.coco.api.modle.Bot;
import com.rw.coco.handler.message.event.CocoMessageEvent;
import com.rw.coco.handler.message.reply.ReplyHandler;
import com.rw.coco.util.CocoCommandUtil;
import com.rw.coco.util.CocoReplyUtil;
import com.rw.tool.util.string.StringFormatter;
import com.rw.tool.util.string.StringUtil;

/**
 * 机器人总开关指令
 */
public class  SwitchOnOFFReplyHandler implements ReplyHandler {
    @Override
    public boolean trigger(CocoMessageEvent cocoMessageEvent) {
        if (!cocoMessageEvent.hasPrefix()) {
            return false;
        }

        // 如果不是超级管理员，直接返回
        if (!cocoMessageEvent.getAccountModel().isSuperAdmin()) {
            return false;
        }

        // 开启、关闭指令
        String switchOn = CocoCommandUtil.COMMAND_PROP.get(CocoCommandUtil.SWITCH_ON);
        String switchOff = CocoCommandUtil.COMMAND_PROP.get(CocoCommandUtil.SWITCH_OFF);

        // 返回指令是否匹配
        return StringUtil.equalsIgnoreCase(cocoMessageEvent.getMessage(), switchOn) ||
                StringUtil.equalsIgnoreCase(cocoMessageEvent.getMessage(), switchOff);
    }

    @Override
    public void handler(CocoMessageEvent cocoMessageEvent) {
        // 开启、关闭指令
        String switchOn = CocoCommandUtil.COMMAND_PROP.get(CocoCommandUtil.SWITCH_ON);
        String switchOff = CocoCommandUtil.COMMAND_PROP.get(CocoCommandUtil.SWITCH_OFF);

        // 三大基础元素
        Bot bot = cocoMessageEvent.getBot();
        Account sender = cocoMessageEvent.getSender();
        CocoLogger cocoLogger = cocoMessageEvent.getCocoLogger();

        if (StringUtil.equalsIgnoreCase(cocoMessageEvent.getMessage(), switchOn)) {
            cocoMessageEvent.getPersistenceMapper().botSwitchOn(bot.getId());
            cocoMessageEvent.sendBack(CocoReplyUtil.REPLY_PROP.get(CocoReplyUtil.BOT_SWITCH_ON));

            // 输出日志
            final String switchOnLog = "得到 {}({}) 开启骰娘指令，{}({}) 开启！";
            String msg = StringFormatter.format(switchOnLog, sender.getNick(), sender.getId(), bot.getName(),
                    bot.getId());
            cocoLogger.info(msg);
        } else if (StringUtil.equalsIgnoreCase(cocoMessageEvent.getMessage(), switchOff)) {
            cocoMessageEvent.getPersistenceMapper().botSwitchOff(bot.getId());
            cocoMessageEvent.sendBack(CocoReplyUtil.REPLY_PROP.get(CocoReplyUtil.BOT_SWITCH_OFF));

            // 输出日志
            final String switchOffLog = "得到 {}({}) 关闭骰娘指令，{}({}) 关闭！";
            String msg = StringFormatter.format(switchOffLog, sender.getNick(), sender.getId(), bot.getName(),
                    bot.getId());
            cocoLogger.info(msg);
        }
    }
}
